package cn.net.isir.controller.manager;

import cn.net.isir.common.ResultObject;
import cn.net.isir.common.TokenManager;
import cn.net.isir.entity.*;
import cn.net.isir.service.*;
import cn.net.isir.service2.MinipIndexDataService;
import cn.net.isir.service2.ShopService;
import cn.net.isir.utils.DateUtils;
import cn.net.isir.utils.ExcelExportUtils;
import cn.net.isir.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author liuxubo
 * @filename TurnShopController.java
 * @package cn.net.isir.controller.manager
 * @email lxb@isir.net.cn
 * @date 2019/03/12
 * @comment
 * @since 1.8
 */
@RestController
@RequestMapping("/shopturn")
public class TurnShopController {
    @Resource
    private ShopService shopService;
    @Resource
    private TurnShopService turnShopService;
    @Resource
    private CRMUserManagerService crmUserManagerService;
    @Resource
    private MinipIndexDataService minipIndexDataService;
    @Resource
    private FactorService factorService;
    @Resource
    private TurnService turnService;
    @Resource
    private BankCardService bankCardService;


    /**
     * 店铺结转列表
     *
     * @param shop 店铺
     * @return 列表
     */
    @RequestMapping(value = "/listByUser", method = RequestMethod.GET)
    public ResultObject getListByUser(Shop shop) {
        //查询所有子用户
        Set<String> userIds = crmUserManagerService.getSalesmanIdByUserId(TokenManager.getTokenId());
       userIds.add(TokenManager.getTokenId());
        if (userIds.size() == 0) {
            return new ResultObject(501, "no salesman", new PageInfo<>());
        }
        String saleIds = StringUtils.collectionsToCommas(userIds);

        //处理中文无法检索
        if(StringUtils.isNotBlank(shop.getName())){
            try {
                shop.setName(URLDecoder.decode(shop.getName(),StandardCharsets.UTF_8.name()));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        // 获取带分页的店铺列表
        PageInfo pageInfo = shopService.selectShopListByUserIds(saleIds,
                shop.getSalesmanCode(), shop.getName(),
                shop.getStartTime(),shop.getEndTime(),
                shop.getPageNo(), shop.getPageSize());
        JSONObject jo = JSONObject.parseObject(JSON.toJSONString(pageInfo));

//        salesmanId
        // 获取列表
        List<Shop> shopList = pageInfo.getList();
        JSONArray ja = new JSONArray();
        for (Shop s : shopList) {
            JSONObject subJO = JSONObject.parseObject(JSON.toJSONString(s));
            TurnShop ts = new TurnShop();
            ts.setShopId(s.getId());
            ts = turnShopService.selectOne(ts);
            if (ts != null) {
                Turn turn = new Turn();
                turn.setId(ts.getTurnId());
                turn = turnService.selectOne(turn);
                subJO.put("isTurned", 1);
                BigDecimal turnFee = ts.getTurnFee().setScale(3, BigDecimal.ROUND_HALF_UP);
                subJO.put("turnfee", turnFee);
                subJO.put("turnTime",turn.getTurnTime());

            } else {
                // 查询订单信息
                subJO.put("isTurned", 0);
                String salesmanId = s.getSalesmanCode();
                String shopId = s.getId();
                List<TimeRange> timeRangeList = crmUserManagerService.getTimeRangeList(salesmanId);
                // 查询店铺营业额信息
                BigDecimal bigDecimal = minipIndexDataService.queryShopIntervalFlow(timeRangeList, shopId,
                        DateUtils.getCurrentMonthStartTime(), DateUtils.getCurrentMonthEndTime());
                Factor factor = factorService.selectOne(null);
                //转前当月流水总额百分比
                BigDecimal rollBefore = factor.getRollBefore();
                BigDecimal percent = new BigDecimal("100");
                rollBefore = rollBefore.divide(percent);
                bigDecimal = rollBefore.multiply(bigDecimal).setScale(3,BigDecimal.ROUND_HALF_UP);
                subJO.put("turnfee", bigDecimal);
            }
            ja.add(subJO);
        }
        jo.put("list", ja);
        return new ResultObject(200, "success", jo);
    }

    /**
     * 店铺结转列表
     *
     * @param shop 店铺
     * @return 列表
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public ResultObject export(Shop shop, HttpServletRequest request, HttpServletResponse response) {
        //查询所有子用户
        Set<String> userIds = crmUserManagerService.getSalesmanIdByUserId(TokenManager.getTokenId());
        userIds.add(TokenManager.getTokenId());
        if (userIds.size() == 0) {
            return new ResultObject(500, "userId has no salesman", null);
        }
        StringBuilder sb = new StringBuilder();
        userIds.forEach(item -> sb.append(item).append(","));
        String saleIds = "";
        if (sb.length() > 0) {
            saleIds = sb.substring(0, sb.length() - 1);
        }
        // 获取带分页的店铺列表
        PageInfo pageInfo = shopService.selectShopListByUserIds(saleIds,
                shop.getSalesmanCode(), shop.getName(),
                shop.getStartTime(),shop.getEndTime(),
                shop.getPageNo(), shop.getPageSize());
        JSONObject jo = JSONObject.parseObject(JSON.toJSONString(pageInfo));

//        salesmanId
        // 获取列表
        List<Shop> shopList = pageInfo.getList();
        List<TurnShop> turnShopList = turnShopService.selectList(null);

        List<List<Object>> rows = new ArrayList<>();
        List<Object> columns;

        for (TurnShop turnShop : turnShopList) {
            boolean isExist = false;
            for (Shop s : shopList) {
                if (s.getId().equals(turnShop.getShopId())) {
                    isExist = true;
                    break;
                }
            }
            if (isExist) {
                Shop shop1 = shopService.selectByPrimaryKey(turnShop.getShopId());
                BankCard bankCard = new BankCard();
                bankCard.setUserId(shop1.getSalesmanCode());
                BankCard bc = bankCardService.selectOne(bankCard);
                SimpleDateFormat str = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//时间格式
                columns = new ArrayList<>();
                columns.add(bc.getName());
                columns.add(shop1.getName());
                columns.add(str.format(shop1.getCreateTime()));
                columns.add(shop1.getSalesmanCode());
                columns.add(turnShop.getTurnFee());
                columns.add(str.format(turnShop.getCreateTime()));
                columns.add(bc.getCardNo());
                columns.add(bc.getBelongTo());
                rows.add(columns);
            }
        }

        String filename = "转出店铺-" + DateUtils.format(new Date(), "yyyyMMddHHmmss") + ".xls";
//        response.setContentType("application/vnd.ms-excel");
        response.setContentType("application/octet-stream");
//        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment;filename=" +
                new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        try {
            OutputStream os = response.getOutputStream();
            ExcelExportUtils.writeExcelOutputStream(os,
                    new String[]{"人员姓名","店铺名称", "创建时间", "销售ID", "佣金", "转出日期","银行卡卡号","开户行支行"}, rows);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResultObject(200, "success", filename);
    }


}
